<template> 
    <div class="app-container " >        
    <div class="query-wrapper">
      <el-form  class=""  :model="queryParams">  
        <el-row>
            <el-select
              v-model="queryParams.vesselName"
              filterable
              clearable
              placeholder="Vessel"
              style="width:180px"
              @change="selectVessel(queryParams)"
            >
              <el-option :key="item.vesselName" :label="item.vesselName" :value="item.vesselName" v-for="item in vessels">
              </el-option>
            </el-select> 
            &nbsp;&nbsp;
            <el-select v-model="queryParams.voyageNo" filterable clearable placeholder="Voyage"  @change="selectVoyage" style="width:110px">
              <el-option :key="item.voyageNo" :label="item.voyageNo" :value="item.voyageNo" v-for="item in voyages">
              </el-option>
            </el-select> 
            &nbsp;&nbsp;
            <el-select v-model="queryParams.pol" filterable clearable allow-create placeholder="POL">
                <el-option :key="item.portName" :label="item.portName" :value="item.portName" v-for="item in pols">
                </el-option>
          </el-select>
          &nbsp;&nbsp;
        <el-select v-model="queryParams.pod" filterable clearable allow-create placeholder="POD">
          <el-option :key="item.portName" :label="item.portName" :value="item.portName" v-for="item in pods">
          </el-option>
        </el-select>          
        &nbsp;&nbsp; 
        <el-button type="primary" icon="search" @click="search">{{ $t("ship.button.search") }}</el-button> 
        <SearchReset :query-params="queryParams" @reset="resetQuery"></SearchReset>
        &nbsp;&nbsp;

      </el-row> 
  </el-form>
</div>
<div  class="query-wrapper" style="margin-top: 20px;margin-bottom: 10px;">
  <el-button type="danger" icon="upload" plain @click="uploadFileForm"> import </el-button>
  <el-button type="success" plain icon="edit" :disabled="!single"  @click="copyClickEvent"> Copy </el-button>
  <el-button type="primary" icon="edit" :disabled="!single" plain @click="editClickEvent">Revise</el-button>
   <el-button type="primary" icon="delete" :disabled="!multiple" plain @click="removeClickEvent">Delete</el-button>
  <el-button type="primary" plain @click="batchFinalize"> Finalize </el-button>
     &nbsp;&nbsp;
  <el-dropdown placement="bottom-start" v-if="listData.length != 0">
    <el-button type="warning" plain icon="download">
      Print<el-icon class="el-icon--right"><arrow-down /></el-icon>
      </el-button>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item v-if="listData.length != 0" fixed="right" @click="exportClickEvent"> As Loaded List</el-dropdown-item>
          <el-dropdown-item v-if="listData.length != 0" fixed="right" @click="exportCargoList"> Cargo List</el-dropdown-item> 
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
 
    <el-table	  
      ref="tableRef"
      stripe
      :data="listData"
      :border:="true"
      max-height="800"
      v-loading="loading" 
      highlight-current-row 
      @sort-change="handleSortChange"   
      @selection-change="handleSelectionChange"
      class="unfreight-table" 
      :show-overflow-tooltip="{effect:'dark'}" 
      :cell-style="{textAlign:'center'}"
	    :row-class-name="tableRowClassName"
    > 
      <el-table-column type="selection"  :selectable="selectable" width="55" /> 
      <el-table-column prop="vesselName" label="Vessel Name" width="140" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column prop="voyageNo" label="Voyage" width="100" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column prop="bookingNo" label="Booking No" width="120"   sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column prop="blNo" label="B/L No" width="150"  />
      <el-table-column prop="status" label="Status" width="110"  >
        <template #default="scope">
            {{bookingStatuss[scope.row.status] }}
        </template> 
      </el-table-column>    
 
      <el-table-column prop="payer" label="Freight Payable Party" width="200" sortable="custom" :sort-orders="['descending', 'ascending']"/> 	  
       <el-table-column prop="destinationCountry" label="Destination Country" width="200" /> 	  
       <el-table-column prop="transferStation" label="T/S" width="200" /> 	  

       <el-table-column prop="pol" label="POL" width="180">
         <template #default="scope">
          {{scope.row.pol}}
          <div v-if="scope.row.oldPol" style="color: #757373;font-size: 10px;"  >({{scope.row.oldPol}})</div>
        </template> 
      </el-table-column>
      <el-table-column prop="pod" label="POD"  width="180">
        <template #default="scope">
          {{scope.row.pod}}
          <div style="color: #757373;font-size: 10px;" v-if="scope.row.oldPod">({{scope.row.oldPod}})</div>
      </template> 
      </el-table-column>
      <el-table-column prop="finalDischarge" label="PFD" width="200" /> 	  
      <el-table-column prop="brand" label="Brand" width="100" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column prop="model" label="Model"  width="100" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column prop="cargoType" label="Cargo Type" width="170"   :sort-orders="['descending', 'ascending']"/>     
      <el-table-column prop="totalUnits" label="Total Units" width="120"  :sort-orders="['descending', 'ascending']"/>
      <el-table-column prop="unitLength" label="Length(m)" width="110"  :sort-orders="['descending', 'ascending']"/> 
      <el-table-column prop="unitWidth" label="Width(m)" width="110"  :sort-orders="['descending', 'ascending']"/>
      <el-table-column prop="unitHeight" label="Height(m)" width="110"  :sort-orders="['descending', 'ascending']"/>
      <el-table-column prop="unitCbm" label="Unit Cbm" width="90"  :sort-orders="['descending', 'ascending']"/>
         <el-table-column prop="totalVolume" :label="'Total Volume'+'\n'+'（cbm）'" width="120" align="center">
	  	  	<template #header>
           Total Volume<br/>（cbm）
        </template> 
	  </el-table-column> 
    <el-table-column
        prop="unitWeight"
        label=""
        width="180"  align="center"
      >
        <template #header>
          <span>Unit Weight({{ unitWeightFilter.text }})</span>
          <el-select
            ref="unitWeightRef"
            v-model="unitWeightFilter"
            class="el-select_dropMenu"
            placeholder="choose"
            value-key="value"
            @change="handleUnitWeightChange"
            @mouseenter="showUnitWeightMenu"
          >
            <el-option :key="item.value" :label="item.text" :value="item" v-for="item in unitWeightFilterOptions" />
          </el-select>
        </template>
        <template #default="{ row: { unitWeight } }">
          <span>{{ unitWeight ? (unitWeight / unitWeightFilter.value) : '' }}</span>
        </template>
      </el-table-column>    
	  
    <el-table-column prop="totalWeight" :label="'Total Weight'+'\n'+'(kg)'" width="120" align="center" > 
	    <template #header>
        Total Weight<br/>(kg)
      </template> 
	  </el-table-column> 
       <el-table-column prop="channel" label="Booking Channel" width="200" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column prop="terminal" :label="'Terminal Ground' +'\n' +'Service Provider'" width="150"  >
	       <template #header>
             Terminal Ground<br/> Service Provider 
        </template> 
	    </el-table-column> 	  
      <el-table-column prop="shipper" label="Shipper" width="200" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column prop="consignee" label="Consignee" width="200"   :sort-orders="['descending', 'ascending']"/>
      <el-table-column prop="notifyParty" label=" Notify Party" width="300"  :sort-orders="['descending', 'ascending']"/>  
      <el-table-column prop="lashingHookFront" :label= "'Lashing Hook'+ '\n' + '  (FRONT)'" width="120" align="center">
	    <template #header>
            Lashing Hook<br/>  (FRONT)
        </template>
        <template #default="scope">
            {{lashHookStatus[scope.row.lashingHookFront] }}
        </template> 
      </el-table-column>
      <el-table-column prop="lashingHookRear" :label="'Lashing Hook'+ '\n' + '  (REAR)'" width="120" align="center">
	    <template #header>
            Lashing Hook<br/>  (REAR)
        </template> 
        <template #default="scope">
            {{lashHookStatus[scope.row.lashingHookRear] }}
        </template> 
      </el-table-column>  
      <!-- <el-table-column prop="carType" :label="'New Vehicle/' + '\n' + 'Used Vehicle'" width="120" align="center">
	  	 <template #header>
           New Vehicle<br/> Used Vehicle
        </template> 
	  </el-table-column>   -->
      <el-table-column prop="fuelType" label="Fuel Type" width="90"  :sort-orders="['descending', 'ascending']"/>
      <el-table-column prop="shippingTerms" :label="'Freight' +'\n' +'Rate Term'" width="120" align="center">
	  	<template #header>
           Freight<br/>  Rate Term
        </template> 
	  </el-table-column>  	  
    <!-- <el-table-column prop="spareLocation" :label="'Spare Parts Location' + '\n' + '（Inside Vehicle / On Deck）'" width="230" align="center"> 
	  	  	<template #header>
          Spare Parts Location<br/>（Inside Vehicle / On Deck）
        </template> 
	  </el-table-column>  --> 
      <!-- <el-table-column label="Operation" align="center" fixed="right" width="100" v-hasPermi="['draft:edit']">
        <template #default="scope">
          <span class="btn-primary" v-if="scope.row.id != null"  @click="editClickEvent(scope.row)">revise</span
          >&nbsp;&nbsp;
          <span class="btn-primary" v-if="scope.row.status != 3  && scope.row.status !=null"  @click="removeClickEvent(scope.row)">{{ $t("ship.button.remove") }}</span>
          &nbsp;&nbsp; 
        </template>
      </el-table-column> -->
    </el-table>  

    <pagination
      v-show="total > 0"
      :total="total"
      :page="queryParams.pageNum"
      :limit="queryParams.pageSize"
      @pagination="pageQuery"
      style="float: right"
    /> 

    <el-dialog :width="1100" destroy-on-close draggable :title="dialogTitle" v-model="reviseDialogFormVisible">
      <el-form :model="reviseParam" :rules="addRules" ref="custForm">
        <el-row>
          <el-col :span="8">
            <el-form-item label="BOOKING NO" label-width="120px" prop="bookingNo" required>
              <el-select v-model="reviseParam.bookingNo" filterable placeholder="choose bookingNo" @change="hanleBookingNo">
                <el-option
                  :key="item.bookingNo"
                  :label="item.bookingNo"
                  :value="item.bookingNo"
                  v-for="item in bookingNos"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="table-boxs">
          <el-button @click="addItem(reviseParam.bookingNo,reviseParam.pol,reviseParam.pod )" type="primary" plain icon="Plus" :disabled="reviseParam.bookingNo == null">Add</el-button>
          <br />
          <br />
          <el-form class="table-box" :rules="rules" style="width:4500px" ref="formRef" :model="formObj">
            <el-table :data="formObj.recordData" class="detail-table" stripe :border="true">              
              <el-table-column prop="defultRule"  label="Booking Channel" width="220" align="center">
                <template #default="scope">
                  <el-form-item
                    :prop="'recordData.' + scope.$index + '.channel'"  
                    required
                    :rules="rules.defultRule"
                  >
                    <el-input  autosize v-model="scope.row.channel" class="ipt" placeholder="Please input" />
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column prop="terminal" :label="'Terminal Ground' + '\n' + 'Service Provider'" width="220" align="center">
                <template #default="scope">
                  <el-form-item
                    :prop="'recordData.' + scope.$index + '.terminal'"
                     :rules="rules.defultRule"
                  >
                    <el-input type="textarea" autosize v-model="scope.row.terminal" class="ipt" placeholder="Please input" />
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column prop="payer" label="Freight Payable Party" width="220" align="center">
                <template #default="scope">
                  <el-form-item
                    :prop="'recordData.' + scope.$index + '.payer'"
                    :rules="rules.defultRule"
                  >
                  <el-select v-model="formParam.payer" filterable >
                    <el-option  :key="item" :label="item"  :value="item" v-for="item in clients"  />
                  </el-select>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column prop="shipper" label="Shipper" width="220" align="center">
                <template #default="scope">
                  <el-form-item
                    :prop="'recordData.' + scope.$index + '.shipper'"
                     :rules="rules.defultRule"
                  >
                    <el-input type="textarea" autosize v-model="scope.row.shipper" class="ipt" style="text-align: center" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="consignee" label="Consignee" width="220" align="center">
                <template #default="scope">
                  <el-form-item
                    :prop="'recordData.' + scope.$index + '.consignee'"
                     :rules="rules.defultRule"
                  >
                    <el-input type="textarea" autosize v-model="scope.row.consignee" style="text-align: center" />
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column prop="notifyParty" label="Notify Party" width="220" align="center">
                <template #default="scope">
                  <el-form-item
                    :prop="'recordData.' + scope.$index + '.notifyParty'"
                    :rules="rules.defultRule">
                    <el-input type="textarea" autosize v-model="scope.row.notifyParty" class="ipt" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="pol" label="POL" width="200" align="center">
                <template #default="scope">
                  <el-form-item
                    :prop="'recordData.' + scope.$index + '.pol'" 
                  > 
                  <el-input  v-model="scope.row.pol" class="ipt" readonly/>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="pod" label="POD" width="200" align="center">
                <template #default="scope">
                  <el-form-item
                    :prop="'recordData.' + scope.$index + '.pod'" 
                  > 
                  <el-input  v-model="scope.row.pod" class="ipt" readonly/>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="brand" label="Brand" width="200" align="center">
                <template #default="scope">
                  <el-form-item
                    :prop="'recordData.' + scope.$index + '.brand'"
                    :rules="rules.defultRule"
                  >
                    <el-select
                      v-model="scope.row.brand"
                      class="ipt"
                      clearable
                      filterable
                      allow-create
                      @change="handBrand(scope.row.brand)"
                    >
                      <el-option :key="item" :label="item" :value="item" v-for="item in brands" />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="model" label="Model" width="200" align="center">
                <template #default="scope">
                  <el-form-item
                    :prop="'recordData.' + scope.$index + '.model'"
                     :rules="rules.defultRule"
                  >
                    <el-select v-model="scope.row.model" class="ipt" filterable allow-create @change="handleModel(scope.row)">
                      <el-option :key="item.name" :label="item.name" :value="item.name" v-for="item in models" />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="cargoType" label="Cargo Type" width="200" align="center">
                <template #default="scope">
                  <el-form-item v-if="scope.row.id != null"
                    :prop="'recordData.' + scope.$index + '.cargoType'"
                     :rules="rules.defultRule">
                    <el-select v-model="scope.row.cargoType" > 
                      <el-option v-for="item in cargo_type" :key="item.label" :label="item.label" :value="item.label" />
                    </el-select> 
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="cargoDesc" label="Cargo Description" width="140" align="center">
                <template #default="scope">
                  <el-form-item
                    :prop="'recordData.' + scope.$index + '.cargoDesc'"
                     :rules="rules.defultRule"
                  >
                    <el-input type="textarea" autosize v-model="scope.row.cargoDesc" style="text-align: center" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="lashHookFront" :label="'Lashing Hook' + '\n' + '(FRONT)' + '\n' + '（Yes / No)'" width="120" align="center">
                <template #default="scope">
                  <el-form-item
                    :prop="'recordData.' + scope.$index + '.lashHookFront'" 
                  >
                    <el-select v-model="scope.row.lashHookFront" filterable placeholder="choose">
                      <el-option :key="index" :label="item" :value="index" v-for="(item, index) in lashHookStatus"> </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="lashHookYear" :label="'Lashing Hook' + '\n' + '(YEAR)' + '\n' + '（Yes / No)'" width="130px" align="center">
                <template #default="scope">
                  <el-form-item
                    :prop="'recordData.' + scope.$index + '.lashHookYear'" 
                  >
                    <el-select v-model="scope.row.lashHookYear" filterable placeholder="choose">
                      <el-option :key="index" :label="item" :value="index" v-for="(item, index) in lashHookStatus"> </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <!-- <el-table-column prop="carType" :label="'New Vehicle /' + '\n' + 'Used Vehicle'" width="120" align="center">
                <template #default="scope">
                  <el-form-item
                    :prop="'recordData.' + scope.$index + '.carType'"
                     :rules="rules.defultRule"
                  >
                  <el-select v-model="scope.row.carType">
                    <el-option :key="item" :label="item" :value="item" v-for="item in carTypes"> </el-option>
                  </el-select>
                </el-form-item>  
                </template>
              </el-table-column> -->
              <el-table-column prop="fuelType" label="Fuel Type" width="120" align="center">
                <template #default="scope">
                  <el-form-item
                    :prop="'recordData.' + scope.$index + '.fuelType'"
                     :rules="rules.defultRule"
                  >
                  <el-select v-model="scope.row.fuelType" filterable>
                    <!-- <el-option :key="item" :label="item" :value="item" v-for="item  in fuelTypes"> </el-option> -->
                    <el-option v-for="item in fuel_type" :key="item.label" :label="item.label" :value="item.label" />
                  </el-select>
                  </el-form-item>
                  <!-- <el-input    v-model="scope.row.ev"  style="text-align: center;"/> -->
                </template>
              </el-table-column>
              <el-table-column prop="unitLength" label="Length(m)" width="150" align="center">
                <template #default="scope">
                  <el-form-item
                    :prop="'recordData.' + scope.$index + '.unitLength'"
                     :rules="rules.defultRule"
                  >
                    <el-input-number v-model="scope.row.unitLength" class="ipt" :precision="3" :min="0" :max="1000"/>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="unitWidth" label="Width(m)" width="150" align="center">
                <template #default="scope">
                  <el-form-item
                    :prop="'recordData.' + scope.$index + '.unitWidth'"
                     :rules="rules.defultRule"
                  >
                    <el-input-number v-model="scope.row.unitWidth" class="ipt" :precision="3" :min="0" :max="1000"/>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="unitHeight" label="Height(m)" width="150" align="center">
                <template #default="scope">
                  <el-form-item
                    :prop="'recordData.' + scope.$index + '.unitHeight'"
                    :rules="rules.defultRule"
                  >
                    <el-input-number v-model="scope.row.unitHeight" class="ipt" :precision="3" :min="0" :max="1000"/>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="shippingTerms" label="Freight Rate Term" width="120" required align="center">
                <template #default="scope">
                  <el-form-item
                    :prop="'recordData.' + scope.$index + '.shippingTerms'" 
                  >
                    <el-select v-model="scope.row.shippingTerms" filterable>
                      <el-option v-for="item in freight_rate_term" :key="item.label" :label="item.label" :value="item.label" />
                  </el-select>
                  </el-form-item> 
                </template>
              </el-table-column> 

              <el-table-column prop="unitWeight" :label="'Unit Weight' + '\n' + '(kg)'" width="170" align="center">
                <template #default="scope">
                  <el-form-item
                    :prop="'recordData.' + scope.$index + '.unitWeight'"
                     :rules="rules.defultRule"
                  >
                    <el-input-number v-model="scope.row.unitWeight" class="ipt" />
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column prop="totalUnits" label="Total Units" width="170" align="center">
                <template #default="scope">
                  <el-form-item
                    :prop="'recordData.' + scope.$index + '.totalUnits'"
                     :rules="rules.defultRule"
                  >
                    <el-input-number v-model="scope.row.totalUnits" class="ipt" />
                  </el-form-item>
                </template>
              </el-table-column>
                      <!--四舍五入，保留3位小数  -->
              <!-- <el-table-column prop="totalVolume" :label="'total volume' + '\n' + '（cbm）'">
                <template #default="scope">
          
                  {{
                    (
                      (scope.row.unitLength || 0) *
                      (scope.row.unitWidth || 0) *
                      (scope.row.unitHeight || 0) *
                      (scope.row.totalUnits || 0)
                    ).toFixed(2)
                  }}
                </template>
              </el-table-column> -->
                <!--四舍五入，保留3位小数    -->
              <!-- <el-table-column prop="totalWeight" :label="'total weight' + '\n' + '(kg)'">
                <template #default="scope"> 
                  {{ (scope.row.totalUnits || 0) * (scope.row.unitWeight || 0) }}
                </template>
              </el-table-column> -->
              <!-- <el-table-column prop="spareQty" :label="'Spare Parts ' + '\n' + 'Qty(Pcs)'" width="200" align="center">
                <template #default="scope">
                  <el-form-item>
                    <el-input-number v-model="scope.row.spareQty" class="ipt" />
                  </el-form-item>
                </template>
              </el-table-column> -->
              <!-- <el-table-column prop="spareLocation" :label="'Spare Parts Location' + '\n' + '（Inside Vehicle / On Deck）'" width="200" align="center">
                <template #default="scope">
                  <el-form-item> 
                    <el-select v-model="scope.row.spareLocation" filterable>
                      <el-option v-for="item in spareParts" :key="item" :label="item" :value="item" />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column> -->
              <!-- <el-table-column prop="spareVolume" :label="'Spare' + '\n' + 'Parts' + '\n' + 'volume（cmdb）'" width="170" align="center">
                <template #default="scope">
                  <el-form-item>
                    <el-input-number v-model="scope.row.spareVolume" class="ipt" />
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column prop="spareWeight" :label="'Spare Parts' + '\n' + 'Weight(kg)'" width="200" align="center">
                <template #default="scope">
                  <el-form-item>
                    <el-input-number v-model="scope.row.spareWeight" class="ipt" />
                  </el-form-item>
                </template>
              </el-table-column> -->
              <el-table-column prop="remark" label="Remarks" align="center" width="200"> 
                <template #default="scope">
                  <el-form-item>
                    <el-input v-model="scope.row.remark"/>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="Operation" width="160" align="center">
                <template #default="scope">
                  <el-button @click="deleteItem(scope.$index)" icon="Delete" />
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviseDialogFormVisible = false">{{ $t("ship.button.cancel") }}</el-button> 
          <el-button type="primary" @click="submitReviseForm">{{ $t("ship.button.submit") }}</el-button>
        </span>
      </template>
    </el-dialog>
    
    <el-dialog class="edit_dialog" destroy-on-close draggable :title="dialogTitle" v-model="dialogFormVisible">
        <el-form :model="formParam" :rules="rules" ref="custForm">
          <el-row>
            {{ formParam }}
            <el-col :span="12">
              <el-form-item label="Booking No" label-width="200px" prop="bookingNo" required>
                <el-input   v-model="formParam.bookingNo" readonly/> 
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Bl No" label-width="170px" prop="blNo" required>
                <el-input   v-model="formParam.blNo" readonly></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="Booking channel" label-width="200px" prop="channel" required>
                <el-input type="textarea" v-model="formParam.channel"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Terminal Ground Service Provider" label-width="210px" prop="terminal" required>
                <el-input type="textarea" v-model="formParam.terminal"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="Freight Payable Party" label-width="170px" prop="payer" required>
                <el-select v-model="formParam.payer" filterable >
                  <el-option  :key="item" :label="item"  :value="item"  v-for="item in clients"  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Shipper" label-width="170px" prop="shipper" required>
                <el-input type="textarea" v-model="formParam.shipper"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="Consignee" label-width="120px" prop="consignee" required>
                <el-input type="textarea" v-model="formParam.consignee"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Notify Party" label-width="120px" prop="notifyParty" required>
                <el-input type="textarea" v-model="formParam.notifyParty"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="POL" label-width="120px" prop="pol" required>
                <el-select v-model="formParam.pol" filterable @change="hanlePol(formParam)">
                  <el-option
                        :key="item.portName"
                        :label="item.countryCode + item.portCode"
                        :value="item.portName"
                        v-for="item in pols"
                      />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="POD" label-width="120px" prop="pod" required>
                <el-select v-model="formParam.pod" filterable>
                  <el-option
                        :key="item.portName"
                        :label="item.countryCode + item.portCode"
                        :value="item.portName"
                        v-for="item in pods"
                      />
                </el-select>
              </el-form-item>
            </el-col>
        
            <el-col :span="8">
              <el-form-item label="Brand" label-width="200px" prop="brand" required>
                <el-select v-model="formParam.brand" filterable @chang="handBrand" clearable allow-create  @change="handBrand(formParam.brand)">
                  <el-option :key="item" :label="item" :value="item" v-for="item in brands" />
                </el-select>
              </el-form-item>
            </el-col> 
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="Model" label-width="120px" prop="model" required>
                <el-select v-model="formParam.model" class="ipt" filterable allow-create @change="handleModel(formParam)">
                      <el-option :key="item.name" :label="item.name" :value="item.name" v-for="item in models" />
                    </el-select>
              </el-form-item>
            </el-col> 
            <el-col :span="8"> 
              <el-form-item label="Cargo Type" prop="cargoType" label-width="100">
                <el-select v-model="formParam.cargoType"  > 
                  <el-option v-for="item in cargo_type" :key="item.label" :label="item.label" :value="item.label" />
                </el-select> 
              </el-form-item>  
          </el-col> 
            <el-col :span="8">
              <el-form-item label="Cargo Description" label-width="120px" prop="cargoDesc">
                <el-input  v-model="formParam.cargoDesc"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="Lashing Hook (FRONT)" label-width="180px" prop="lashingHookFront">
                <el-select v-model="formParam.lashingHookFront" filterable>
                  <el-option :key="index" :label="item" :value="index" v-for="(item, index) in lashHookStatus" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Lashing Hook (REAR)" label-width="180px" prop="lashingHookRear">
                <el-select v-model="formParam.lashingHookRear" filterable>
                  <el-option :key="index" :label="item" :value="index" v-for="(item, index) in lashHookStatus" />
                </el-select>
              </el-form-item>
            </el-col> 
            </el-row>
            <el-row> 
            <!-- <el-col :span="12">
              <el-form-item label="New Vehicle / Used Vehicle" label-width="180px" prop="carType" v-if="formParam.cargoType!='Parts'" required>
                <el-select v-model="formParam.carType" filterable>
                  <el-option :key="item" :label="item" :value="item" v-for="(item) in carTypes" />
                </el-select>
              </el-form-item>
              <el-form-item label="New Vehicle / Used Vehicle" label-width="120px" prop="carType" v-else>
                <el-select v-model="formParam.carType" filterable>
                  <el-option :key="item" :label="item" :value="item" v-for="(item) in carTypes" />
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="Fuel Type" label-width="120px" prop="fuelType"  v-if="formParam.cargoType!='Parts'" required>
                <el-select v-model="formParam.fuelType" filterable placeholder="choose ">
                  <el-option :key="item" :label="item" :value="item" v-for="item in fuelTypes"> </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="Fuel Type" label-width="120px" prop="fuelType"  v-else>
                <el-select v-model="formParam.fuelType" filterable placeholder="choose ">
                  <el-option :key="item" :label="item" :value="item" v-for="item in fuelTypes"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="Length(m)" label-width="120px" prop="unitLength" required>
                <el-input-number v-model="formParam.unitLength" :precsion="3" :min="0" :max="100" />
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="Width(m)" label-width="120px" prop="unitWidth" required>
                <el-input-number v-model="formParam.unitWidth" :precsion="3" :min="0" :max="100" />
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item label="Height(m)" label-width="240px" prop="unitHeight" required>
                <el-input-number v-model="formParam.unitHeight" :precsion="3" :min="0" :max="100" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
 
            <el-col :span="8">
              <el-form-item label="unit weight (kg)" label-width="120px" prop="unitWeight" required>
                <el-input type="number" v-model="formParam.unitWeight" :min="0" :max="100000" style="width: 150px;" />
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="total units" label-width="120px" prop="totalUnits" required>
                <el-input-number v-model="formParam.totalUnits" :min="0" :max="10000" />
              </el-form-item>
            </el-col> 
          <!-- <el-row>
            <el-col :span="12">
              <el-form-item label="total volume（cbm）" label-width="200px">
                <template>
                  {{ (formParam.unitLength * formParam.unitHeight * formParam.unitWidth * formParam.totalUnits).toFixed(2) }}
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Total Weight (kg)" label-width="200px" prop="totalWeight" required>
                <template>
                  {{ ((formParam.totalUnits || 0) * (formParam.unitWeight || 0)).toFixed(2) }}
                </template> 
              </el-form-item>
            </el-col>
          </el-row> -->
 
            <!-- <el-col :span="12">
              <el-form-item label="Spare Parts Qty （Pcs)" label-width="170px" prop="spareQty">
                <el-input-number v-model="formParam.spareQty" />
              </el-form-item>
            </el-col> -->
            <el-col :span="9">
              <el-form-item label="Spare Parts Location（in cab / on deck）" label-width="240px" prop="spareLocation">
                <el-select v-model="formParam.spareLocation" filterable>
                      <el-option v-for="item in spareParts" :key="item" :label="item" :value="item" />
                    </el-select>
              </el-form-item>
            </el-col>
          </el-row> 
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">{{ $t("ship.button.cancel") }}</el-button>
            <el-button type="primary" @click="submitForm">{{ $t("ship.button.submit") }}</el-button>
          </span>
        </template>
      </el-dialog>    


      <el-dialog class="edit_dialog" destroy-on-close draggable :title="dialogTitle" v-model="viewDialogFormVisible">
        <el-form :model="formParam"   ref="custForm">
          <el-row>
            <el-col :span="12">
              <el-form-item label="Booking No" label-width="200px" prop="bookingNo" required>
                  {{ formParam.bookingNo }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Bl No" label-width="170px" prop="blNo" required>
                {{ formParam.blNo }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="Booking channel" label-width="200px" prop="channel" >
                {{ formParam.channel }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Terminal Ground Service Provider" label-width="170px" prop="terminal" required>
                {{ formParam.terminal }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="Freight Payable Party" label-width="170px" prop="payer" required>
                {{ formParam.payer }} 
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Shipper" label-width="170px" prop="shipper" required>
                {{ formParam.shipper }} 
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="Consignee" label-width="120px" prop="consignee" required>
                {{ formParam.consignee }} 
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Notify Party" label-width="120px" prop="notifyParty" required>
                {{ formParam.notifyParty }} 
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="POL" label-width="120px" prop="pol" required>
                {{ formParam.pol }} 
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="POD" label-width="120px" prop="pod" required>
                    {{ formParam.pod }}  
              </el-form-item>
            </el-col>
        
            <el-col :span="8">
              <el-form-item label="brand" label-width="200px" prop="brand" required>
                {{ formParam.brand }} 
              </el-form-item>
            </el-col> 
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="model" label-width="120px" prop="model" required>
                {{ formParam.model }} 
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="Cargo Type" label-width="120px" >
                {{ formParam.cargoType }} 
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="Cargo Description" label-width="120px" prop="cargoDesc">
                {{ formParam.cargoDesc }} 
              </el-form-item>
            </el-col>
          </el-row> 

          <el-row>
            <!-- <el-col :span="12">
              <el-form-item label="New Car / Used Car" label-width="120px" prop="carType">
                 {{ formParam.carType }}
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="FuelType" label-width="120px" prop="fuelType" required>
                {{ formParam.fuelType }}
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="Length(m)" label-width="120px" prop="unitLength" required>
                 {{ formParam.unitLength }} 
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="Width(m)" label-width="120px" prop="unitWidth" required>
                {{ formParam.unitWidth }} 
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="Height(m)" label-width="120px" prop="unitHeight" required>
                {{ formParam.unitHeight }} 
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!-- <el-col :span="8">
              <el-form-item label="unit cbm" label-width="120px">
                <template>
                  {{ (formParam.unitLength * formParam.unitHeight * formParam.unitWidth).toFixed(2) }}
                </template>
              </el-form-item>
            </el-col> -->
            <el-col :span="8">
              <el-form-item label="unit weight (kg)" label-width="120px" prop="unitWeight"  >
                <template default="scope">
                  <el-dropdown>
                    <span class="el-dropdown-link">
                      {{ scope.column.unitWeight }}<i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                          <el-dropdown-menu default="dropdown">
                            <el-dropdown-item>Kg</el-dropdown-item>
                            <el-dropdown-item>Dun</el-dropdown-item> 
                          </el-dropdown-menu>
                  </el-dropdown>
            </template> 
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="total units" label-width="120px" prop="totalUnits" required>
                {{ formParam.totalUnits }} 
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row>
            <el-col :span="12">
              <el-form-item label="total volume（cbm）" label-width="200px">
                <template>
                  {{ (formParam.unitLength * formParam.unitHeight * formParam.unitWidth * formParam.totalUnits).toFixed(2) }}
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Total Weight (kg)" label-width="200px" prop="totalWeight" required>
                <template>
                  {{ ((formParam.totalUnits || 0) * (formParam.unitWeight || 0)).toFixed(2) }}
                </template> 
              </el-form-item>
            </el-col>
          </el-row> -->

          <el-row>
            <!-- <el-col :span="12">
              <el-form-item label="Spare Parts Qty （Pcs)" label-width="170px" >
                {{ formParam.spareQty }} 
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="Spart Parts Location（in cab / on deck）" label-width="230px" prop="spareLocation">
                {{ formParam.spareLocation }} 
              </el-form-item>
            </el-col>
          </el-row>

          <!-- <el-row>
            <el-col :span="12">
              <el-form-item label="Spare Parts volume(cbm)" label-width="200px" prop="spareVolume">
                 {{formParam.spareVolume}}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Spare Parts Weight(kg)" label-width="200px" prop="spareLocation">
                {{formParam.spareLocation}}
              </el-form-item>
            </el-col>
          </el-row> -->
          <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="B/L NO. 提单号" label-width="120px" prop="totalVolume">
            <el-input type="number" v-model="formParam.spareVolume" disabled />
          </el-form-item>
        </el-col>
      </el-row> -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="Remarks" label-width="120px" prop="remark">
                {{formParam.remark}}
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>        
      </el-dialog>   
      <FileUploadStep ref="fileUploadRef" :templateFile="templateFile" :url="downTemplateUrl" 
        :isAlink="false" :queryParams="queryParams" 
        :uploadFileUrl="uploadFileUrl" 
        :fileType="fileType" 
        @update:modelValue="updateFileUpload"  />
  </div>  
</template>
<script lang="ts" setup name="asLoadedList">
// @ts-nocheck

import { ref, onMounted, reactive } from "vue"; 
import { useRouter } from 'vue-router';
import service from "@/utils/request"; 
import {downloadFile} from '@/utils/downloadFile'   
import { useTableDrag } from '@/hooks/useHooks'
import { copyApi,deleteApi } from "@/api/booking/asLoadedlist";
import moment from "moment";
const { tableRef, proxy } = useTableDrag();
const multipleSelection = ref<User[]>([])
const single = ref(false)
const multiple = ref(false)
// 导入功能
const downTemplateUrl=ref('shipping/booking/download/template')
const fileType = ref(['.xlsx', '.xls'])
const fileUploadRef=ref(null)
const uploadFileForm=()=>{
  proxy.$refs["fileUploadRef"].dialogUploadFileForm()
}
let uploadFileUrl = "/shipping/asLoaded/uploadFile"
const updateFileUpload= (data: any) => {
ElNotification.success({
        title: "Prompt information",
        message: data,
        position: "bottom-right"
      });
refreshTable();
};


import { ElNotification, ElMessageBox, ElMessage } from "element-plus";
import SplitModal from "./modules/SplitModal.vue"; 

const spareParts = ["Inside Vehicle","On Deck"] 
const loading = ref(false)
let clients = reactive([])

let tableRowClassName=(row)=> {
    for (const rs of multipleSelection.value) {
		if (row.row.id === rs.id) 
		{
		  return 'warning_row';
		} 
    }
	return '';
}
const handleSelectionChange = (val: User[]) => {   
  multipleSelection.value = val 
  single.value =  (multipleSelection.value.length==1)
  multiple.value = multipleSelection.value.length; 
}
const resetQuery = (data:any) => {
  Object.assign(queryParams, data)
  listData.value = []   
  total.value = 0
}
const selectable = (row: User) => (row.id != null & row.status != 1)

const router = useRouter();
const templateFile = "booking.xlsx"
// 重量单位换算
const unitWeightRef = ref(null)
const unitWeightFilter = ref({ text: 'kg', value: 1 });
const unitWeightFilterOptions = reactive([{ text: 'kg', value: 1 }, { text: 'ton', value: 1000 }]);
const handleUnitWeightChange = (item: any) => {
  unitWeightFilter.value = item
}
const showUnitWeightMenu = () => {
  unitWeightRef?.value?.toggleMenu()
}

const onSuceess = ()=>{
 refreshTable()
}

// 删除选择销售
const deleteRoleRef= ref(null);
let deleteRoleVisible = ref(false);
let deleteRoleForm = ref({ userId: '', id: '' });
const roleFormRules = ref({
  userId: [{ required: true, message: "user is required" }],
});
let sales = reactive([]);
const getRoleList = () => {
  getUserByRoleApi({ roleName: 'sales' }).then((res: any) => {
    sales = (res.data || []).map(({ id, username }) => ({ id, username }))
  })
}
const submitDeleteForm = () => {
  deleteRoleRef.value.validate(valid => {
    if (valid) {
      deleteApi(deleteRoleForm.value).then(() => {
        deleteRoleVisible.value = false;
        refreshTable();
        // @ts-ignore
        ElNotification.success({
          title: "Prompt information",
          message: "Delete successfully!",
          position: "bottom-right"
        });
      })
    }
  })  
}
 

// 行展开
let expands = ref([])
const handleExpandChange = (row: any, expandedRows: any) => {
  if (expandedRows.length && expandedRows.find((item: any) => item.seqNo === row.seqNo)) {
    historyApi(row.id).then((res: any) => {
      row.children = res.data || []
    })
    expands.value = expandedRows.map((item: any) => item.seqNo)
  }
} 
 
const handleClose = async(id)=>{
  ElMessageBox.confirm("CONFIRM TO FINALIZE", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel",
  }).then(async () => {
     await service.put(`shipping/freighted/close/${id}`)
     ElNotification.success({
      title: "Prompt information",
      message: "close booking success!",
      position: "bottom-right"
    });
    refreshTable()
  })
}
const custForm = ref(null);
const dialogTitle = ref("");
const initForm = {
  id: null,
  bookingNo: null,
  vesselName: null,
  vesselCode: null,
  voyageNo: null,
  carrier: null,
  carrierCode: null, 
  channel: null,
  terminal: null,
  payer: null,
  shipper: null,
  consignee: null,
  notifyParty: null,
  pol: null,
  portCode: null,
  pod: null,
  brand: null,
  model: null,
  cargoType: null,
  cargoDesc: null,
  lashingHookFront: null,
  lashingHookRear: null,
  carType: null,
  fuelType: null,
  unitLength: null,
  unitWidth: null,
  unitHeight: null,
  unitCbm: null,
  unitWeight: null,
  totalUnits: null,
  totalWeight: null,
  totalVolume: null, 
  spareLocation: null, 
  remark: null,
  blNo: null,
  bookingStatus:null,
  bookings: [] as any
};

const initForm1 = {
  id: null,
  carrier: null,
  carrierCode: null,
  voyageNo: null,  
  vesselName: null,
  vesselCode: null,
  portCode: null,
  salesId: null,
  bookings: [] as any
};
const formParam = reactive(Object.assign({}, initForm));
const addFormParam = reactive(Object.assign({}, initForm1));
const reviseParam = reactive(Object.assign({}, initForm));
const total = ref(0);

const rules = ref({
  carrier: [{ required: true, message: "carrier is required" }],
  voyageNo: [{ required: true, message: "voyage is required" }],
  defultRule:[
    {
      required: true,
      message: 'Mandatory Field'
    }
  ]
});
 
const addRules = ref({
  carrier: [{ required: true, message: "carrier is required" }],
  voyageNo: [{ required: true, message: "voyage is required" }],
  defultRule:[
    {
      required: true,
      message: 'Mandatory Field'
    }
  ]
});

let bookingNos =reactive([])
const lashHookStatus = [ "No","Yes"];
const carTypes = ["New", "Used"];
const fuelTypes = ["Non-EV", "BEV", "HEV", "PHEV", "EREV", "FCV", "EV", "OTHER"];

var queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  id: null, 
  vesselName: null,
  voyageNo: null, 
  bookingNo:null,
  orderByColumn: undefined,
  isAsc: undefined
});

const freightRateTerms = ["FLT","FIO","FILO","LIFO"]
let carriers = ref([] as any);
let brands = ref([]);
let models = ref([] as any);
let vessels = reactive([] as any);
let voyages = reactive([] as any);
let statuss = ["loaded", "","waiting list"] 
let ports = ref([] as any);
let recordData = ref([] as any);
const listData = ref([] as any);
let pols = ref([] as any);
let pods = ref([] as any);
const refreshTable =  () => { 
  loading.value = true
  let result =  service.get("/shipping/freighted/getTable", { params: queryParams}).then((result) => {
    let seqNo = 1
    listData.value = result.data 
    loading.value=false
    total.value = result.total
  });	  
};

const dialogFormVisible = ref(false); 
const addDialogFormVisible = ref(false);
const reviseDialogFormVisible = ref(false);
const viewDialogFormVisible = ref(false);
const editClickEvent = (row: any) => {
  dialogTitle.value = "Update";
  dialogFormVisible.value = true;
  Object.keys(initForm).forEach(k => (formParam[k] = multipleSelection.value[0][k]));
  isAdd = false;
};

const removeClickEvent = () => { 
  let ids = multipleSelection.value.map(item => item.id)
  let id= ids.join(',')
  ElMessageBox.confirm("Confirm to Remove the data？", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel",
  }).then(async () => {
    deleteApi({ id }).then(() => {
      refreshTable();
      ElNotification.success({
        title: "Prompt information",
        message: "Send the delete information to the sales to confirm!",
        position: "bottom-right"
      });
    }) 
  })
};

let index = 1;
let isAdd = false;
const bookingStatuss =['Not Closed','Closed']
const handleRowDblclick=(row:any)=>{
  dialogTitle.value = "View";
  viewDialogFormVisible.value = true;
  Object.keys(initForm).forEach((k) => (formParam[k] = row[k]));
  isAdd = false;
}

const addClickEvent = () => {
  dialogTitle.value = "Add booking";
  isAdd = true;
  addDialogFormVisible.value = true;
  Object.assign(addFormParam, initForm1);
  formObj.value.recordData = [];

};

const reViseClickEvent = async()=>{  
  dialogTitle.value = "Revise Present";
  isAdd = true;
  reviseDialogFormVisible.value = true;
  Object.assign(reviseParam, initForm1);
  formObj.value.recordData = [];
}

const handleExport = ()=>{ 
  downloadFile('shipping/booking/exportTemplate',queryParams, `booking.xlsx`)
} 

const hanleBookingNo = async()=>{
  let item =bookingNos.find(n=>n.bookingNo == reviseParam.bookingNo)
  
  if(item){
    reviseParam.pol = item.pol
    reviseParam.pod = item.pod
    reviseParam.portCode = item.portCode
    reviseParam.voyageNo = item.voyageNo
    reviseParam.carrier = item.carrier
    reviseParam.carrierCode = item.carrierCode
    reviseParam.vesselName = item.vesselName
    reviseParam.vesselCode = item.vesselCode
    reviseParam.blNo = item.blNo 
  }
}
const resetForm = () => {
  // @ts-ignore
  custForm.value.resetFields();
};

const submitForm = () => { 
  // @ts-ignore
  custForm.value.validate(async valid => {
    if (!valid) {
      // @ts-ignore
      ElNotification.warning({
        title: "Prompt information",
        message: "verification not success！",
        position: "bottom-right"
      });
      return;
    } 

      //formParam.bookingNo = vesselCode + formParam.pol + "24001";
      formParam.unitCbm = (formParam.unitLength * formParam.unitWidth * formParam.unitHeight).toFixed(3);
      formParam.totalVolume = (formParam.unitCbm * formParam.totalUnits).toFixed(3); 
      formParam.totalWeight = formParam.totalUnits * formParam.unitWeight;
      await service[ "put"]("shipping/freighted", formParam);
      // @ts-ignore
      ElNotification.success({
        title: "Prompt information",
        message: "save successful!",
        position: "bottom-right"
      });
 

    dialogFormVisible.value = false;
    refreshTable();
  });
};

const submitReviseForm= ()=>{
// @ts-ignore
  formRef.value.validate(async valid => {
        if (!valid) {
          // @ts-ignore
          ElNotification.warning({
            title: "Prompt information",
            message: "verification not success！",
            position: "bottom-right"
          });
          return;
        }else{
          if(formObj.value.recordData.length === 0){
            ElNotification.warning({
              title: "Prompt information",
              message: "data must input！",
              position: "bottom-right"
            });
            return;
          }
          formObj.value.recordData.forEach((item: any )=> {
            //bookingNo: 船名短代码+港口代码 +年份+顺序号
            item.unitCbm = (item.unitLength * item.unitWidth * item.unitHeight).toFixed(3);
            item.totalVolume = (item.unitCbm * item.totalUnits).toFixed(3);
    
            item.totalWeight = item.totalUnits * item.unitWeight;
          });
          reviseParam.bookings = formObj.value.recordData;
          await service["post"]("shipping/freighted", reviseParam);
          // @ts-ignore
          ElNotification.success({
            title: "Prompt information",
            message: "save successful!",
            position: "bottom-right"
          });
          dialogFormVisible.value = false;
          refreshTable()
        } 
      })
}

const pageQuery = async (e) => {
  queryParams.pageNum = e.page;
  queryParams.pageSize = e.limit;
  refreshTable();
};

const hanlePol = async(row:any)=> {
  let item = pols.value.find(n => n.portName == row.pol);

  if (item) {
    row.portCode = item.countryCode + item.portCode;
  }

  // if (row.pol != null && addFormParam.vesselCode != null) { 
  //   let params = {carrierCode:addFormParam.carrierCode, portCode:row.portCode,voyageNo: addFormParam.voyageNo, vesselCode: addFormParam.vesselCode };
  //   let result = await service.get("/shipping/booking/getAutoData", { params: params });
  //   if (result) {
  //     row.bookingNo = result.data.bookingNo; 
  //   }
  // }
};

const search = () => {  
    localStorage.setItem("asLoadedList",JSON.stringify(queryParams))
  if((queryParams.vesselName == null || queryParams.vesselName == '') && queryParams.status == null && (queryParams.bookingNo == null|| queryParams.bookingNo == '')){
    listData.value = []
    ElMessage.warning( "please choose search item!");
    return
  }
  if(queryParams.voyageNo == null || queryParams.voyageNo == undefined || queryParams.voyageNo == ''){
    ElMessage.warning("please choose voyage to query!");
    return      
  } 
  refreshTable();
};

const exitClickEvent = ()=>{
  queryParams.vesselName = null
  queryParams.bookingNo = null
  queryParams.voyageNo = null
  queryParams.status = null
  listData.value = []
}

const exportClickEvent = async () => {
  downloadFile("/shipping/freighted/export", queryParams, `O_${listData.value[0].vesselName}_${listData.value[0].voyageNo}_${moment( new Date()).format('YYYYMMDDHHmm')}loadingList.xlsx`);
}
const exportCargoList = ()=>{
  downloadFile("/shipping/freighted/exportCargoList", queryParams, `${listData.value[0].vesselName}_${listData.value[0].voyageNo}_exportCargoList_${moment( new Date()).format('YYYYMMDDHHmm')}.xlsx`);
}
 
const uploadFile = async (event:any) => {
  if (event.target == null || event.target.files[0] == null) {
    return;
  }
  const formData = new FormData();
  formData.append("file", event.target.files[0]);
  await service["post"]("shipping/booking/uploadFile", formData);
   
  //refreshTable()
  // @ts-ignore
  ElNotification.success({
    title: "Prompt information",
    message: "save successful!",
    position: "bottom-right"
  });
       
};

const handleSortChange = async (column: any) => {
  console.log(column)
  queryParams.orderByColumn = column.prop;
  queryParams.isAsc = column.order; //动态取值排序顺序
  refreshTable();
};
 

const selectVessel =(form)=>{ 
  if(form.vesselName != null && form.vesselName != undefined){
    form.voyageNo = null
    let params = {vesselName: form.vesselName} 
    let item = vessels.find(n=>n.vesselName == form.vesselName) 
    if(item){
      form.vesselCode = item.vesselCode  
      voyages = item.schedules
    } 
  } 
}

const selectVoyage = (value)=>{
   //@ts-ignore
  let item = voyages.find(n=>n.voyageNo == value)
  if(item){
    pods.value = item.pods
    pols.value = item.pols
  }
}

const defaultSort = ref({ prop: "updateTime", order: "descending" });
 
const formRef = ref(null);
let formObj = ref({
  recordData: []
});

const addItem = (bookingNo:String,pol:String,pod:String,blNo:string) => {   
  formObj.value.recordData.push({
    id: recordData.value.length + 1,
    bookingNo:bookingNo,
    channel: "",
    terminal: "",
    payer: "",
    shipper: "",
    consignee: "",
    notifyParty: "",
    pol: pol,
    pod: pod,
    brand: "",
    model: "",
    cargoDesc: "",
    unitLength: null,
    unitWidth: null,
    unitHeight: null,
    unitCbm: null,
    unitWeight: null,
    totalUnits: null,
    totalVolume: null,
    totalWeight: null,
    spareQty: null,
    spareLocation: null,
    spareVolume: null,
    spareWeight: null,
    blNo: blNo
  });
};

const deleteItem = (index) => {
  if (formObj.value.recordData != null && formObj.value.recordData.length > 1) {
    formObj.value.recordData.splice(index, 1);
  }
  for (let i in formObj.value.recordData) {
    formObj.value.recordData[i].id = parseInt(i) + 1;
  }
};
 
const selectComapny = () => {
  let item = carriers.value.find(n => n.carrierName == addFormParam.carrier);
  if (item) {
    addFormParam.carrierCode = item.carrierCode;
  }
};

const handBrand = async (value) => {
  if (brands.value.includes(value)) {
    let params = { brand: value };
    let result = await service.get("/shipping/vehicleModel/getByBrand", {
      params: params
    });
    models.value = result.data; 
  }
};

const handleStatus=(row:any)=>{
  if(row.status != null && row.status != 0){
    ElMessageBox.confirm("Confirm to update the Booking Status？", "Confirmation Information", {
        type: "warning",
        confirmButtonText: "Confirm",
        cancelButtonText: "Cancel",
      }).then(async () => {
        let params = {id:row.id,status:row.status}  ;
        await service.put(`shipping/booking/updateBooking`, params);
        ElNotification.success({
          title: "Prompt information",
          message: "Update booking status success!",
          position: "bottom-right"
        });
      });
  }
}

const importFile = ()=>{
   ElMessageBox.confirm("Confirm to import FIle?", "Confirmation Information", {
        type: "warning",
        confirmButtonText: "Confirm",
        cancelButtonText: "Cancel",
      }).then(async () => {
        let params = {id:row.id,status:row.status}  ;
        await service.put(`shipping/freighted/updateBooking`, params);
        ElNotification.success({
          title: "Prompt information",
          message: "Update booking status success!",
          position: "bottom-right"
        });
      });
}

const batchFinalize = async()=>{
  const ids = [];
    for (const rs of multipleSelection.value) {
        ids.push (rs.id)
    }
    if(ids.length <=0){
      // @ts-ignore
      ElNotification.warning({ title: "Prompt information", message: "choose data to batch finalize！", position: "bottom-right" });
      return;
    }
     ElMessageBox.confirm("Confirm to finalize the booking？", "Confirmation Information", {
        type: "warning",
        confirmButtonText: "Confirm",
        cancelButtonText: "Cancel",
      }).then(async () => {
      await service.put(`shipping/freighted/close/`+ids);
      ElNotification.success({
        title: "Prompt information",
        message: "batch finalize the data success!",
        position: "bottom-right"
      });
      refreshTable()
  })
}

const handleModel = (row:any) => {
  let item = models.value.find(n => n.brand == row.brand && n.name == row.model); 
  if (item) {
    row.fuelType = item.fuelType;
    row.unitHeight = item.unitHeight;
    row.unitWdith = item.unitWidth;
    row.unitLength = item.unitLength;
  }
};
 
let cargo_type = reactive([])
let fuel_type = reactive([])
let freight_rate_term = reactive([])
onMounted(async () => {
  index=0
  let result = await service.get("/shipping/schedule/getAllSchedule");
  if (result) {
    vessels = result.data;
  } 

  result = await service.get("/shipping/vehicleModel/brands");
  if (result) {
    brands.value = result.data;
  }
  service.get("/shipping/client/getAllName").then(res=>{  clients = res.data})
  
  var ss= localStorage.getItem("asLoadedList")
  if(ss){
    var tt=JSON.parse(ss)
    console.log(tt,ss)
    
    queryParams.vesselName = tt.vesselName
    queryParams.bookingNo = tt.bookingNo
    queryParams.voyageNo = tt.voyageNo
    queryParams.status = tt.status
    listData.value = []
	} 
  refreshTable();

  const res  = await proxy.useDict("cargo_type","fuel_type","freight_rate_term");
  cargo_type = res.cargo_type
  fuel_type = res.fuel_type
  freight_rate_term = res.freight_rate_term
});

 const copyClickEvent =()=>{
  let item = multipleSelection.value[0]  
  ElMessageBox.confirm("Confirm to Copy the selected As Loaded？", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel",
  }).then(async () => {
      copyApi(item).then(() => { 
      refreshTable();
      // @ts-ignore
      ElNotification.success({
        title: "Prompt information",
        message: "Delete successfully!",
        position: "bottom-right"
      });
    }) 
  }) 
}
</script>
<style lang="scss">

.edit_dialog {
  width: 1100px !important;
  max-width: 95vw;
  .el-select {
    width: 100%;
  }
  element.style {
    width: 1000;
  }
  .el-icon-upload {
    font-size: 2rem;
    cursor: pointer;
  }
}

.el-table {
  .cell {
    // white-space: pre-line !important;
  }
}

.table-boxs {
  width: 100%;
  overflow-x: auto;
}
.unfreight-table tr td:nth-child(1) {
    width: 1px;overflow:hidden !important;
}
.unfreight-table tr th:nth-child(1) {
    width: 1px;overflow:hidden !important;
}
.el-table_1_column_2{
    width: 100px;
}
.unfreight-table tr th:nth-child(2) {
    width: 100px;

}
.el-table__expand-icon{
width: 1px;overflow:hidden !important
}

.unfreight-table {   
  .el-table__expand-column .cell {
    display: block;
  }
  .el-table__fixe {
    z-index: 100;
  }
  .unfreight-table-history {
    margin-left: 60px;
    width: calc(100% - 220px);
    .el-table__row {
      background-color: #f0f0f0;
      .cell-bg-color {
        background-color: #ef9c9c !important;
      }
    }
  }
}

.el-table_1_column_1 {
	width: 0 !important;
	overflow:hidden !important;
}

</style>
<style lang="scss" scoped>
.el-table_1_column_1 {
	width: 0 !important;
	overflow:hidden !important;
}
.table-box {
  .el-form-item {
    margin-bottom: 18px;
  }
}
.block2 {
 min-height: 60px;
 .el-row {
   margin:10px 10px 20px;
  }
}
.example-showcase .el-loading-mask {
  z-index: 9;
}
 
.warning_row .el-table__cell{
   background:#6eadff !important;
}
</style>